<!DOCTYPE html>


<html lang="en">


<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    springboot中dubbo服务导出-2 |  一曲秋殇
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/images/myfavicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-dubbo/springboot中dubbo服务导出-2"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  springboot中dubbo服务导出-2
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-2/" class="article-date">
  <time datetime="2021-12-13T05:51:40.041Z" itemprop="datePublished">2021-12-13</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E5%90%8E%E5%8F%B0/">后台</a> / <a class="article-category-link" href="/categories/%E5%90%8E%E5%8F%B0/java/">java</a> / <a class="article-category-link" href="/categories/%E5%90%8E%E5%8F%B0/java/dubbo/">dubbo</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">3.4k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">16 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/hint.css/2.4.1/hint.min.css"><blockquote>
<p>上一篇<a href="/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-1/">“springboot中dubbo服务导出-1”</a>分析到了RegistryProtocol#export方法，这一部分主要分析该方法中本地服务暴露部分，剩下的远程服务注册在下一章分析<br>以下分析是基于dubbo2.7.8</p>
</blockquote>
<p> RegistryProtocol#export方法体如下，这一部分主要该方法中前半部分的代码<br>  <figure class="highlight java"><figcaption><span>RegistryProtocol.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">  <span class="keyword">public</span> &lt;T&gt; <span class="function">Exporter&lt;T&gt; <span class="title">export</span><span class="params">(<span class="keyword">final</span> Invoker&lt;T&gt; originInvoker)</span> <span class="keyword">throws</span> RpcException </span>&#123;</span><br><span class="line">      URL registryUrl = getRegistryUrl(originInvoker);</span><br><span class="line">      URL providerUrl = getProviderUrl(originInvoker);</span><br><span class="line">      <span class="keyword">final</span> URL overrideSubscribeUrl = getSubscribedOverrideUrl(providerUrl);</span><br><span class="line">      <span class="keyword">final</span> OverrideListener overrideSubscribeListener = <span class="keyword">new</span> OverrideListener(overrideSubscribeUrl, originInvoker);</span><br><span class="line">      overrideListeners.put(overrideSubscribeUrl, overrideSubscribeListener);</span><br><span class="line">      providerUrl = overrideUrlWithConfig(providerUrl, overrideSubscribeListener);</span><br><span class="line">      <span class="keyword">final</span> ExporterChangeableWrapper&lt;T&gt; exporter = doLocalExport(originInvoker, providerUrl);</span><br><span class="line">      <span class="comment">//----------------------------------------------分割线，前面是服务启动相关，下面是注册到注册中心相关-------------------------------------------------------------------</span></span><br><span class="line">      <span class="keyword">final</span> Registry registry = getRegistry(originInvoker);</span><br><span class="line">      <span class="keyword">final</span> URL registeredProviderUrl = getUrlToRegistry(providerUrl, registryUrl);</span><br><span class="line">      <span class="keyword">boolean</span> register = providerUrl.getParameter(REGISTER_KEY, <span class="keyword">true</span>);</span><br><span class="line">      <span class="keyword">if</span> (register) &#123;</span><br><span class="line">          register(registryUrl, registeredProviderUrl);</span><br><span class="line">      &#125;</span><br><span class="line">      registerStatedUrl(registryUrl, registeredProviderUrl, register);</span><br><span class="line">      exporter.setRegisterUrl(registeredProviderUrl);</span><br><span class="line">      exporter.setSubscribeUrl(overrideSubscribeUrl);</span><br><span class="line">      registry.subscribe(overrideSubscribeUrl, overrideSubscribeListener);</span><br><span class="line">      notifyExport(exporter);</span><br><span class="line">      <span class="keyword">return</span> <span class="keyword">new</span> DestroyableExporter&lt;&gt;(exporter);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><br>  下面对RegistryProtocol#export方法中前半部分代码进行详细分析</p>
<h4 id="1-获取注册的url对象"><a href="#1-获取注册的url对象" class="headerlink" title="1. 获取注册的url对象"></a>1. 获取注册的url对象</h4><hr>
<p>代码如下</p>
<figure class="highlight java"><figcaption><span>RegistryProtocol.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> URL <span class="title">getRegistryUrl</span><span class="params">(Invoker&lt;?&gt; originInvoker)</span> </span>&#123;</span><br><span class="line">    URL registryUrl = originInvoker.getUrl();</span><br><span class="line">    <span class="comment">//判断协议是否为registry</span></span><br><span class="line">    <span class="keyword">if</span> (REGISTRY_PROTOCOL.equals(registryUrl.getProtocol())) &#123;</span><br><span class="line">        <span class="comment">//取出registryUrl中registry参数的值（即注册协议），url中没有指定的话就使用默认的dubbo协议</span></span><br><span class="line">        String protocol = registryUrl.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY);</span><br><span class="line">        <span class="comment">//设置registryUrl的协议为上一步获取的协议，并移除registryUrl中指定的协议参数</span></span><br><span class="line">        registryUrl = registryUrl.setProtocol(protocol).removeParameter(REGISTRY_KEY);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> registryUrl;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>getRegistryUrl这个方法主要是将原始Invoker中的协议类型修改为url中指定的注册协议（没指定默认为dubbo），如原始url为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=c3-provider&amp;dubbo=2.0.2&amp;<span class="built_in">export</span>=dubbo%3A%2F%2F192.168.10.120%3A20880%2Fcom.alibaba.dubbo.demo.DemoService%3Fanyhost%3Dtrue%26application%3Dc3-provider%26bind.ip%3D192.168.10.120%26bind.port%3D20880%26default%3Dtrue%26deprecated%3Dfalse%26dubbo%3D2.0.2%26dynamic%3Dtrue%26generic%3Dfalse%26interface%3Dcom.alibaba.dubbo.demo.DemoService%26metadata-type%3Dremote%26methods%3DsayHello%26pid%3D2508%26qos.enable%3Dfalse%26release%3D2.7.8%26side%3Dprovider%26timestamp%3D1614828359691&amp;pid=2508&amp;qos.enable=<span class="literal">false</span>&amp;registry=zookeeper&amp;release=2.7.8&amp;timestamp=1614828359691</span><br></pre></td></tr></table></figure>
<p>则替换后的url为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">zookeeper://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=c3-provider&amp;dubbo=2.0.2&amp;<span class="built_in">export</span>=dubbo%3A%2F%2F192.168.10.120%3A20880%2Fcom.alibaba.dubbo.demo.DemoService%3Fanyhost%3Dtrue%26application%3Dc3-provider%26bind.ip%3D192.168.10.120%26bind.port%3D20880%26default%3Dtrue%26deprecated%3Dfalse%26dubbo%3D2.0.2%26dynamic%3Dtrue%26generic%3Dfalse%26interface%3Dcom.alibaba.dubbo.demo.DemoService%26metadata-type%3Dremote%26methods%3DsayHello%26pid%3D2508%26qos.enable%3Dfalse%26release%3D2.7.8%26side%3Dprovider%26timestamp%3D1614828359691&amp;pid=2508&amp;qos.enable=<span class="literal">false</span>&amp;release=2.7.8&amp;timestamp=1614828359691</span><br></pre></td></tr></table></figure>
<h4 id="2-获取暴露的url对象"><a href="#2-获取暴露的url对象" class="headerlink" title="2. 获取暴露的url对象"></a>2. 获取暴露的url对象</h4><hr>
<p>这一步则主要取出原始url中的export参数值做解码后转换成URL对象返回，代码如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> URL <span class="title">getProviderUrl</span><span class="params">(<span class="keyword">final</span> Invoker&lt;?&gt; originInvoker)</span> </span>&#123;</span><br><span class="line">    String export = originInvoker.getUrl().getParameterAndDecoded(EXPORT_KEY);</span><br><span class="line">    <span class="keyword">if</span> (export == <span class="keyword">null</span> || export.length() == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;The registry export url is null! registry: &quot;</span> + originInvoker.getUrl());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> URL.valueOf(export);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如原始url为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">registry://127.0.0.1:2181/org.apache.dubbo.registry.RegistryService?application=c3-provider&amp;dubbo=2.0.2&amp;<span class="built_in">export</span>=dubbo%3A%2F%2F192.168.10.120%3A20880%2Fcom.alibaba.dubbo.demo.DemoService%3Fanyhost%3Dtrue%26application%3Dc3-provider%26bind.ip%3D192.168.10.120%26bind.port%3D20880%26default%3Dtrue%26deprecated%3Dfalse%26dubbo%3D2.0.2%26dynamic%3Dtrue%26generic%3Dfalse%26interface%3Dcom.alibaba.dubbo.demo.DemoService%26metadata-type%3Dremote%26methods%3DsayHello%26pid%3D2508%26qos.enable%3Dfalse%26release%3D2.7.8%26side%3Dprovider%26timestamp%3D1614828359691&amp;pid=2508&amp;qos.enable=<span class="literal">false</span>&amp;registry=zookeeper&amp;release=2.7.8&amp;timestamp=1614828359691</span><br></pre></td></tr></table></figure>
<p>则取出export值为：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dubbo://192.168.10.120:20880/com.alibaba.dubbo.demo.DemoService?anyhost=<span class="literal">true</span>&amp;application=c3-provider&amp;bind.ip=192.168.10.120&amp;bind.port=20880&amp;default=<span class="literal">true</span>&amp;deprecated=<span class="literal">false</span>&amp;dubbo=2.0.2&amp;dynamic=<span class="literal">true</span>&amp;generic=<span class="literal">false</span>&amp;interface=com.alibaba.dubbo.demo.DemoService&amp;metadata-type=remote&amp;methods=sayHello&amp;pid=2508&amp;qos.enable=<span class="literal">false</span>&amp;release=2.7.8&amp;side=provider&amp;timestamp=1614828359691</span><br></pre></td></tr></table></figure>
<h4 id="3-订阅配置中心配置变更事件"><a href="#3-订阅配置中心配置变更事件" class="headerlink" title="3. 订阅配置中心配置变更事件"></a>3. 订阅配置中心配置变更事件</h4><hr>
<blockquote>
<p>在<a href="/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-1/#2-1-1-startConfigCenter%E8%BF%9E%E6%8E%A5%E9%85%8D%E7%BD%AE%E4%B8%AD%E5%BF%83%E5%8A%A0%E8%BD%BD%E6%95%B0%E6%8D%AE">“springboot中dubbo服务导出-1#2.1.1”</a>中将一个compositeDynamicConfiguration 对象设置到了Environment中，compositeDynamicConfiguration组合对象中的那些DynamicConfiguration添加了对配置中心/dubbo/config目录的监听</p>
</blockquote>
<p>   这一步会调用overrideUrlWithConfig方法，方法代码如下：<br>   <figure class="highlight java"><figcaption><span>RegistryProtocol.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> URL <span class="title">overrideUrlWithConfig</span><span class="params">(URL providerUrl, OverrideListener listener)</span> </span>&#123;</span><br><span class="line">    providerUrl = providerConfigurationListener.overrideUrl(providerUrl);</span><br><span class="line">    <span class="comment">//ServiceConfigurationListener构造中会添加监听到DynamicConfiguration中，详细见下面分析</span></span><br><span class="line">    ServiceConfigurationListener serviceConfigurationListener = <span class="keyword">new</span> ServiceConfigurationListener(providerUrl, listener);</span><br><span class="line">    serviceConfigurationListeners.put(providerUrl.getServiceKey(), serviceConfigurationListener);</span><br><span class="line">    <span class="keyword">return</span> serviceConfigurationListener.overrideUrl(providerUrl);</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure><br>   ServiceConfigurationListener实现了ConfigurationListener接口，其的构造如下<br>   <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ServiceConfigurationListener</span><span class="params">(URL providerUrl, OverrideListener notifyListener)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.providerUrl = providerUrl;</span><br><span class="line">    <span class="comment">//这个notifyListener的doOverrideIfNecessary方法实现了配置变更后的更新处理</span></span><br><span class="line">    <span class="keyword">this</span>.notifyListener = notifyListener;</span><br><span class="line">    <span class="comment">//这个initWith方法中最终会将ServiceConfigurationListener作为监听器循环添加到compositeDynamicConfiguration组合对象的DynamicConfiguration中</span></span><br><span class="line">    <span class="comment">//当当前服务配置发生变更时会调用下面的notifyOverrides方法进行处理</span></span><br><span class="line">    <span class="keyword">this</span>.initWith(DynamicConfiguration.getRuleKey(providerUrl) + CONFIGURATORS_SUFFIX);</span><br><span class="line">&#125;    </span><br><span class="line"></span><br><span class="line"><span class="comment">//AbstractConfiguratorListener#process中会调用该notifyOverrides方法进行处理覆盖逻辑</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">notifyOverrides</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    notifyListener.doOverrideIfNecessary();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="4-执行服务本地暴露操作（启动服务）"><a href="#4-执行服务本地暴露操作（启动服务）" class="headerlink" title="4. 执行服务本地暴露操作（启动服务）"></a>4. 执行服务本地暴露操作（启动服务）</h4><hr>
<p>本地服务暴露的代码如下：</p>
<figure class="highlight java"><figcaption><span>RegistryProtocol.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> &lt;T&gt; <span class="function">ExporterChangeableWrapper&lt;T&gt; <span class="title">doLocalExport</span><span class="params">(<span class="keyword">final</span> Invoker&lt;T&gt; originInvoker, URL providerUrl)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//获取缓存key，主要是将原始Invoker中的export值去除dynamic和enabled参数得出得Url字符值作为key</span></span><br><span class="line">    String key = getCacheKey(originInvoker);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> (ExporterChangeableWrapper&lt;T&gt;) bounds.computeIfAbsent(key, s -&gt; &#123;</span><br><span class="line">        <span class="comment">//将originInvoker和providerUrl包装成InvokerDelegate对象，InvokerDelegate类实现了Invoker接口，包装后对象中的url属性值会被赋值为为providerUrl</span></span><br><span class="line">        Invoker&lt;?&gt; invokerDelegate = <span class="keyword">new</span> InvokerDelegate&lt;&gt;(originInvoker, providerUrl);</span><br><span class="line">        <span class="comment">//这一步的主要操作就是通过 protocol.export获取Exporter对象然后包装成ExporterChangeableWrapper对象进行返回</span></span><br><span class="line">        <span class="comment">//由于invokerDelegate中的url为providerUrl（协议参数值为dubbo，协议自适应拓展会优先获取url中的协议参数值），所以最终调用的是DubboProtocol#export方法</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ExporterChangeableWrapper&lt;&gt;((Exporter&lt;T&gt;) protocol.export(invokerDelegate), originInvoker);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>DubboProtocol#export方法精简后的代码如下</p>
<figure class="highlight java"><figcaption><span>DubboProtocol.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function">Exporter&lt;T&gt; <span class="title">export</span><span class="params">(Invoker&lt;T&gt; invoker)</span> <span class="keyword">throws</span> RpcException </span>&#123;</span><br><span class="line">    <span class="comment">//取出url值，这个invoker就是上面doLocalExport方法中的那个invokerDelegate对象</span></span><br><span class="line">    URL url = invoker.getUrl();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//取出暴露服务的key，该key主要是由组名称+服务名称+版本号+端口组成（组名称和版本号不指定则没有），示例如下：</span></span><br><span class="line">    <span class="comment">//groupName/com.study.api.UserService:1.1.0:20880</span></span><br><span class="line">    String key = serviceKey(url);</span><br><span class="line">    <span class="comment">//通过invoker, key, exporterMap这三个参数实例化一个DubboExporter对象，exporterMap主要用于缓存已经暴露的DubboExporter</span></span><br><span class="line">    DubboExporter&lt;T&gt; exporter = <span class="keyword">new</span> DubboExporter&lt;T&gt;(invoker, key, exporterMap);</span><br><span class="line">    <span class="comment">//将暴露的服务缓存起来</span></span><br><span class="line">    exporterMap.put(key, exporter);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//开启服务器端口</span></span><br><span class="line">    openServer(url);</span><br><span class="line">    optimizeSerialization(url);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> exporter;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>openServer方法如下，主要是从url中取出主机+端口作为key，然后判断该key对应的ProtocolServer没有被缓存过，没有被缓存的话则通过createServer方法创建ProtocolServer然后缓存</p>
<figure class="highlight java"><figcaption><span>DubboProtocol.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">openServer</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">    String key = url.getAddress();</span><br><span class="line">    <span class="keyword">boolean</span> isServer = url.getParameter(IS_SERVER_KEY, <span class="keyword">true</span>);</span><br><span class="line">    <span class="keyword">if</span> (isServer) &#123;</span><br><span class="line">        ProtocolServer server = serverMap.get(key);</span><br><span class="line">        <span class="keyword">if</span> (server == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">                server = serverMap.get(key);</span><br><span class="line">                <span class="keyword">if</span> (server == <span class="keyword">null</span>) &#123;</span><br><span class="line">                    <span class="comment">//该key没有被缓存则调用createServer并缓存</span></span><br><span class="line">                    serverMap.put(key, createServer(url));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            server.reset(url);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>精简后的createServer代码如下</p>
<figure class="highlight java"><figcaption><span>DubboProtocol.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> ProtocolServer <span class="title">createServer</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">    url = URLBuilder.from(url)</span><br><span class="line">            <span class="comment">//在服务器关闭时发送只读事件，默认情况下启用</span></span><br><span class="line">            .addParameterIfAbsent(CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString())</span><br><span class="line">            <span class="comment">//设置心跳heartbeat为60000</span></span><br><span class="line">            .addParameterIfAbsent(HEARTBEAT_KEY, String.valueOf(DEFAULT_HEARTBEAT))</span><br><span class="line">            <span class="comment">//添加codec参数值为dubbo</span></span><br><span class="line">            .addParameter(CODEC_KEY, DubboCodec.NAME)</span><br><span class="line">            .build();</span><br><span class="line">    <span class="comment">//获取key为server的参数值，如果没有指定则默认为netty</span></span><br><span class="line">    String str = url.getParameter(SERVER_KEY, DEFAULT_REMOTING_SERVER);</span><br><span class="line">    <span class="comment">//如果已经存在的Transporter拓展中没有拓展名为上一步获取的值，则抛出异常</span></span><br><span class="line">    <span class="keyword">if</span> (str != <span class="keyword">null</span> &amp;&amp; str.length() &gt; <span class="number">0</span> &amp;&amp; !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RpcException(<span class="string">&quot;Unsupported server type: &quot;</span> + str + <span class="string">&quot;, url: &quot;</span> + url);</span><br><span class="line">    &#125;        </span><br><span class="line">    ExchangeServer server;</span><br><span class="line">    <span class="comment">//这个Exchangers.bind是个门面方法，里面涉及到的逻辑下面会展开分析</span></span><br><span class="line">    server = Exchangers.bind(url, requestHandler);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> DubboProtocolServer(server);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h5 id="4-1-执行交换层的绑定方法Exchangers-bind"><a href="#4-1-执行交换层的绑定方法Exchangers-bind" class="headerlink" title="4.1 执行交换层的绑定方法Exchangers.bind"></a>4.1 执行交换层的绑定方法Exchangers.bind</h5><p>createServer方法中最核心的就是<code>Exchangers.bind(url, requestHandler);</code>这个方法调用了，先来看下交互层相关的类图<br><img src="http://img.luobiao.vip/img/20210312080008.png"><br>原图链接：<a href="">https://www.processon.com/view/link/604ab02e7d9c08389fd92f57</a></p>
<figure class="highlight java"><figcaption><span>Exchangers.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> ExchangeServer <span class="title">bind</span><span class="params">(URL url, ExchangeHandler handler)</span> <span class="keyword">throws</span> RemotingException </span>&#123;</span><br><span class="line">    <span class="comment">//如果codec参数没有设置则设置默认值为exchange，上面createServer方法中已经codec设置为dubbo了</span></span><br><span class="line">    url = url.addParameterIfAbsent(Constants.CODEC_KEY, <span class="string">&quot;exchange&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> getExchanger(url).bind(url, handler);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><figcaption><span>HeaderExchanger.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> ExchangeServer <span class="title">bind</span><span class="params">(URL url, ExchangeHandler handler)</span> <span class="keyword">throws</span> RemotingException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> HeaderExchangeServer(Transporters.bind(url, <span class="keyword">new</span> DecodeHandler(<span class="keyword">new</span> HeaderExchangeHandler(handler))));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>ExchangeHandlerAdapter，HeaderExchangeHandler，DecodeHandler这三个类都实现了ChannelHandler这个接口<br>HeaderExchangeHandler，DecodeHandler这两个类主要是通过装饰模式对ExchangeHandlerAdapter进行了增强<br>Transporters.bind()方法和Exchangers.bind()一样都是门面方法，最终都是通过自适应拓展根据传入的url获取拓展实现</p>
<h5 id="4-2-执行传输层的绑定方法Transporters-bind"><a href="#4-2-执行传输层的绑定方法Transporters-bind" class="headerlink" title="4.2 执行传输层的绑定方法Transporters.bind"></a>4.2 执行传输层的绑定方法Transporters.bind</h5><figure class="highlight java"><figcaption><span>Transporters.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> RemotingServer <span class="title">bind</span><span class="params">(URL url, ChannelHandler... handlers)</span> <span class="keyword">throws</span> RemotingException </span>&#123;</span><br><span class="line">    ChannelHandler handler;</span><br><span class="line">    <span class="keyword">if</span> (handlers.length == <span class="number">1</span>) &#123;</span><br><span class="line">        handler = handlers[<span class="number">0</span>];</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        handler = <span class="keyword">new</span> ChannelHandlerDispatcher(handlers);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> getTransporter().bind(url, handler);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Transporter默认拓展为netty，对应的拓展实现类为NettyTransporter，该类中bind方法返回的是一个NettyServer实例对象</p>
<figure class="highlight java"><figcaption><span>NettyTransporter.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> RemotingServer <span class="title">bind</span><span class="params">(URL url, ChannelHandler handler)</span> <span class="keyword">throws</span> RemotingException </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> NettyServer(url, handler);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个NettyServer类也实现了ChannelHandler接口，打开netty服务器监听的逻辑在父类AbstractServer构造中，在NettyServer本身的构造中主要是对handler进行了消息派发（Dispatcher）的包装</p>
<figure class="highlight java"><figcaption><span>NettyServer.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">NettyServer</span><span class="params">(URL url, ChannelHandler handler)</span> <span class="keyword">throws</span> RemotingException </span>&#123;</span><br><span class="line">    <span class="comment">//ChannelHandlers.wrap方法将传入的handler（即DecodeHandler）进行了包装</span></span><br><span class="line">    <span class="keyword">super</span>(ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME), ChannelHandlers.wrap(handler, url));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="4-3-执行Dispatcher-dispatch对handler进行包装"><a href="#4-3-执行Dispatcher-dispatch对handler进行包装" class="headerlink" title="4.3 执行Dispatcher#dispatch对handler进行包装"></a>4.3 执行Dispatcher#dispatch对handler进行包装</h5><p>ChannelHandlers#warp方法代码如下，首先会去获取Dispatcher类型的自适应拓展（默认获取到的是AllDispatcher拓展实现），然后调用dispatch方法返回一个AllChannelHandler（这个AllChannelHandler类实现了ChannelHandler接口，主要是对handler消息处理进行了多线程派发）对象作为HeartbeatHandler（对心跳检测包进行处理的Handler）的构造参数，而构造的HeartbeatHandler又作为MultiMessageHandler（支持多消息处理的Handler）的构造参数，最终返回MultiMessageHandler对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">return</span> <span class="keyword">new</span> MultiMessageHandler(<span class="keyword">new</span> HeartbeatHandler(ExtensionLoader.getExtensionLoader(Dispatcher.class)</span><br><span class="line">                .getAdaptiveExtension().dispatch(handler, url)));</span><br></pre></td></tr></table></figure>
<h5 id="4-4-执行NettyServer父类AbstractServer构造"><a href="#4-4-执行NettyServer父类AbstractServer构造" class="headerlink" title="4.4 执行NettyServer父类AbstractServer构造"></a>4.4 执行NettyServer父类AbstractServer构造</h5><figure class="highlight java"><figcaption><span>AbstractServer.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AbstractServer</span><span class="params">(URL url, ChannelHandler handler)</span> <span class="keyword">throws</span> RemotingException </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(url, handler);</span><br><span class="line">    localAddress = getUrl().toInetSocketAddress();</span><br><span class="line">    String bindIp = getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost());</span><br><span class="line">    <span class="keyword">int</span> bindPort = getUrl().getParameter(Constants.BIND_PORT_KEY, getUrl().getPort());</span><br><span class="line">    <span class="keyword">if</span> (url.getParameter(ANYHOST_KEY, <span class="keyword">false</span>) || NetUtils.isInvalidLocalHost(bindIp)) &#123;</span><br><span class="line">        bindIp = ANYHOST_VALUE;</span><br><span class="line">    &#125;</span><br><span class="line">    bindAddress = <span class="keyword">new</span> InetSocketAddress(bindIp, bindPort);</span><br><span class="line">    <span class="keyword">this</span>.accepts = url.getParameter(ACCEPTS_KEY, DEFAULT_ACCEPTS);</span><br><span class="line">    <span class="keyword">this</span>.idleTimeout = url.getParameter(IDLE_TIMEOUT_KEY, DEFAULT_IDLE_TIMEOUT);</span><br><span class="line">    <span class="comment">//该方法中会打开服务监听端口</span></span><br><span class="line">    doOpen();</span><br><span class="line">   </span><br><span class="line">    executor = executorRepository.createExecutorIfAbsent(url);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h6 id="4-4-1-执行AbstractServer-doOpen打开netty服务端监听"><a href="#4-4-1-执行AbstractServer-doOpen打开netty服务端监听" class="headerlink" title="4.4.1 执行AbstractServer#doOpen打开netty服务端监听"></a>4.4.1 执行AbstractServer#doOpen打开netty服务端监听</h6><p>启动服务的时候会添加NettyServerHandler这个Handler，NettyServerHandler中有个ChannelHandler类型的属性，这个属性就是NettyServer本身。</p>
<figure class="highlight java"><figcaption><span>NettyServer.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doOpen</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">    bootstrap = <span class="keyword">new</span> ServerBootstrap();</span><br><span class="line"></span><br><span class="line">    bossGroup = NettyEventLoopFactory.eventLoopGroup(<span class="number">1</span>, <span class="string">&quot;NettyServerBoss&quot;</span>);</span><br><span class="line">    workerGroup = NettyEventLoopFactory.eventLoopGroup(getUrl().getPositiveParameter(IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),<span class="string">&quot;NettyServerWorker&quot;</span>);</span><br><span class="line">    <span class="comment">//这个NettyServerHandler构造中传入NettyServer本身</span></span><br><span class="line">    <span class="keyword">final</span> NettyServerHandler nettyServerHandler = <span class="keyword">new</span> NettyServerHandler(getUrl(), <span class="keyword">this</span>);</span><br><span class="line">    channels = nettyServerHandler.getChannels();</span><br><span class="line"></span><br><span class="line">    bootstrap.group(bossGroup, workerGroup)</span><br><span class="line">            .channel(NettyEventLoopFactory.serverSocketChannelClass())</span><br><span class="line">            .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE)</span><br><span class="line">            .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)</span><br><span class="line">            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)</span><br><span class="line">            .childHandler(<span class="keyword">new</span> ChannelInitializer&lt;SocketChannel&gt;() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(SocketChannel ch)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                    <span class="keyword">int</span> idleTimeout = UrlUtils.getIdleTimeout(getUrl());</span><br><span class="line">                    NettyCodecAdapter adapter = <span class="keyword">new</span> NettyCodecAdapter(getCodec(), getUrl(), NettyServer.<span class="keyword">this</span>);</span><br><span class="line">                    <span class="keyword">if</span> (getUrl().getParameter(SSL_ENABLED_KEY, <span class="keyword">false</span>)) &#123;</span><br><span class="line">                        ch.pipeline().addLast(<span class="string">&quot;negotiation&quot;</span>,</span><br><span class="line">                                SslHandlerInitializer.sslServerHandler(getUrl(), nettyServerHandler));</span><br><span class="line">                    &#125;</span><br><span class="line">                    ch.pipeline()</span><br><span class="line">                            .addLast(<span class="string">&quot;decoder&quot;</span>, adapter.getDecoder())</span><br><span class="line">                            .addLast(<span class="string">&quot;encoder&quot;</span>, adapter.getEncoder())</span><br><span class="line">                            .addLast(<span class="string">&quot;server-idle-handler&quot;</span>, <span class="keyword">new</span> IdleStateHandler(<span class="number">0</span>, <span class="number">0</span>, idleTimeout, MILLISECONDS))</span><br><span class="line">                            <span class="comment">//添加NettyServerHandler</span></span><br><span class="line">                            .addLast(<span class="string">&quot;handler&quot;</span>, nettyServerHandler);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">    ChannelFuture channelFuture = bootstrap.bind(getBindAddress());</span><br><span class="line">    channelFuture.syncUninterruptibly();</span><br><span class="line">    channel = channelFuture.channel();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>NettyServerHandler代码如下：</p>
<figure class="highlight java"><figcaption><span>NettyServerHandler.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//这个handler传入的就是NettyServer</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">NettyServerHandler</span><span class="params">(URL url, ChannelHandler handler)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (url == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;url == null&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (handler == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">&quot;handler == null&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.url = url;</span><br><span class="line">    <span class="keyword">this</span>.handler = handler;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//channelRead方法中调用NettyServer#received</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler);</span><br><span class="line">    handler.received(channel, msg);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//write方法中调用NettyServer#sent</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">write</span><span class="params">(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>.write(ctx, msg, promise);</span><br><span class="line">    NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler);</span><br><span class="line">    handler.sent(channel, msg);</span><br><span class="line">&#125;        </span><br></pre></td></tr></table></figure>
<h6 id="4-4-1-设置AbstractServer线程池属性"><a href="#4-4-1-设置AbstractServer线程池属性" class="headerlink" title="4.4.1 设置AbstractServer线程池属性"></a>4.4.1 设置AbstractServer线程池属性</h6><p>设值的代码如下：</p>
<figure class="highlight java"><figcaption><span>AbstractServer.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//其实此处的ExecutorRepository拓展已经在DubboBootstrap类加载的时候被加载过了，这里直接从缓存中获取该拓展，默认拓展为DefaultExecutorRepository</span></span><br><span class="line"><span class="keyword">private</span> ExecutorRepository executorRepository = ExtensionLoader.getExtensionLoader(ExecutorRepository.class).getDefaultExtension();</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">AbstractServer</span><span class="params">(URL url, ChannelHandler handler)</span> <span class="keyword">throws</span> RemotingException </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    doOpen();</span><br><span class="line">    <span class="comment">//executorRepository值为一个DefaultExecutorRepository对象</span></span><br><span class="line">    executor = executorRepository.createExecutorIfAbsent(url);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过调用DefaultExecutorRepository#createExecutorIfAbsent创建线程池</p>
<figure class="highlight java"><figcaption><span>DefaultExecutorRepository.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> ExecutorService <span class="title">createExecutorIfAbsent</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//EXECUTOR_SERVICE_COMPONENT_KEY值为&quot;java.util.concurrent.ExecutorService&quot;</span></span><br><span class="line">    String componentKey = EXECUTOR_SERVICE_COMPONENT_KEY;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (CONSUMER_SIDE.equalsIgnoreCase(url.getParameter(SIDE_KEY))) &#123;</span><br><span class="line">        <span class="comment">//如果url中的side参数值为consumer，则设置componentKey为consumer</span></span><br><span class="line">        componentKey = CONSUMER_SIDE;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//看data中是否有缓存改componentKey对应的线程池容器，没有的话为该componentKey设置一个ConcurrentHashMap对象</span></span><br><span class="line">    Map&lt;Integer, ExecutorService&gt; executors = data.computeIfAbsent(componentKey, k -&gt; <span class="keyword">new</span> ConcurrentHashMap&lt;&gt;());</span><br><span class="line">    Integer portKey = url.getPort();</span><br><span class="line">    <span class="comment">//看executors缓存中是否有该url端口对应的线程池缓存，没有的话调用下面的createExecutor创建</span></span><br><span class="line">    ExecutorService executor = executors.computeIfAbsent(portKey, k -&gt; createExecutor(url));</span><br><span class="line">    <span class="keyword">if</span> (executor.isShutdown() || executor.isTerminated()) &#123;</span><br><span class="line">        executors.remove(portKey);</span><br><span class="line">        executor = createExecutor(url);</span><br><span class="line">        executors.put(portKey, executor);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> executor;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> ExecutorService <span class="title">createExecutor</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//通过ThreadPool自适应拓展的getExecutor获取线程池，默认的ThreadPool拓展为FixedThreadPool，下面详细分析该类</span></span><br><span class="line">    <span class="keyword">return</span> (ExecutorService) ExtensionLoader.getExtensionLoader(ThreadPool.class).getAdaptiveExtension().getExecutor(url);</span><br><span class="line">&#125;    </span><br></pre></td></tr></table></figure>
<p>ThreadPool自适应拓展默认实现FixedThreadPool的代码如下：</p>
<figure class="highlight java"><figcaption><span>FixedThreadPool.class</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Executor <span class="title">getExecutor</span><span class="params">(URL url)</span> </span>&#123;</span><br><span class="line">    <span class="comment">//获取threadname参数值，没有默认为&quot;Dubbo&quot;，该值将作为线程池创建线程的名称的前缀</span></span><br><span class="line">    String name = url.getParameter(THREAD_NAME_KEY, DEFAULT_THREAD_NAME);</span><br><span class="line">    <span class="comment">//获取threads参数值，没有默认为200，改值将作为线程池核心线程数及最大线程数</span></span><br><span class="line">    <span class="keyword">int</span> threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS);</span><br><span class="line">    <span class="comment">//获取queues参数值，如果没有则默认为0，如果该值为0则使用SynchronousQueue作为线程任务池队列，如果小于0则使用LinkedBlockingQueue队列，如果大于0也使用LinkedBlockingQueue队列，只是队列大小为queues值</span></span><br><span class="line">    <span class="keyword">int</span> queues = url.getParameter(QUEUES_KEY, DEFAULT_QUEUES);</span><br><span class="line">    <span class="comment">//执行创建线池程的操作，这里dubbo自定义了线程池拒绝策略AbortPolicyWithReport</span></span><br><span class="line">    <span class="comment">//该策略主要打印了线程池详细设置参数，线程池当前的状态，拒绝任务的一些详细信息还有当前线程堆栈详情。最后抛出拒绝执行异常，使本次任务失败</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ThreadPoolExecutor(threads, threads, <span class="number">0</span>, TimeUnit.MILLISECONDS,</span><br><span class="line">            queues == <span class="number">0</span> ? <span class="keyword">new</span> SynchronousQueue&lt;Runnable&gt;() :</span><br><span class="line">                    (queues &lt; <span class="number">0</span> ? <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;()</span><br><span class="line">                            : <span class="keyword">new</span> LinkedBlockingQueue&lt;Runnable&gt;(queues)),</span><br><span class="line">            <span class="keyword">new</span> NamedInternalThreadFactory(name, <span class="keyword">true</span>), <span class="keyword">new</span> AbortPolicyWithReport(name, url));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>




<link rel="stylesheet" href="/css/spoiler.css" type="text/css"><script src="/js/spoiler.js" type="text/javascript" async></script> 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=https://luobiao320.gitee.io/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-2/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/dubbo/" rel="tag">dubbo</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/springboot/" rel="tag">springboot</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA/" rel="tag">服务导出</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-3/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            springboot中dubbo服务导出-3
          
        </div>
      </a>
    
    
      <a href="/dubbo/springboot%E4%B8%ADdubbo%E6%9C%8D%E5%8A%A1%E5%AF%BC%E5%87%BA-1/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">springboot中dubbo服务导出-1</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "kHx6wceVXdEyiCrLm0sLAwoF-gzGzoHsz",
    app_key: "ArEdGk6wzHOhrXLiwmClhDNH",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "给我的文章加点评论吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2020-2021
        <i class="ri-heart-fill heart_icon"></i> luobiao
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        Powered by <a href="https://hexo.io" target="_blank">Hexo</a>
        <span class="division">|</span>
        Theme - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      
        <li>
          <a href="http://beian.miit.gov.cn/" target="_black" rel="nofollow">赣ICP备2020014719号-1</a>
        </li>
        
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="http://img.luobiao.vip/53119d0bda706bbe350333137a67ea3e_1.jpg" alt="一曲秋殇"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/dubbo">dubbo</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/spring">spring</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/mysql">mysql</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/img/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->

<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>